# -*- coding: utf-8 -*-
#    CoreDesk - a powerfull jabber client
#    Copyright (C) 2009  Jean-Baptiste Gury <jeanbaptiste.gury@gmail.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
import sqlite3
import CoreDeskTools
import os.path
import os
import time
from account import Account

currentSession = None

class SessionException(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

def createSession(jid, description, server, port, resource, avatar, password):
    id = unicode(int(time.mktime(time.localtime())))
    conn = createSessionDataBase(id)
    cur = conn.cursor()
    cur.execute('''insert into jid(jid) values (?)''', (jid,))
    cur.execute('''select id from jid where jid = ?''', (jid, ))
    id_jid = cur.fetchone()[0]
    cur.execute('''insert into account(id_jid,description, server, port, resource, avatar,password) values(?,?,?,?,?,?,?)''', (id_jid, description, server,  port, resource, avatar,password))
    conn.commit()

def getListSession():
    dir = CoreDeskTools.getCoredeskDir()
    for f in os.listdir(dir):
        s = Session(f)
        print s
        

class Session :
    """This class represents a session for an user.    
    
    """
    def __init__(self,  id):
        self.__accounts = []
        self.__databaseFileName = None
        self.__databaseConnection = None
        self.__loadSession(id)
    
    def __loadSession(self, id):
        """Set instance variables to values for this session
        
        """
        dir = CoreDeskTools.getCoredeskDir()
        self.__databaseFileName = os.path.join(dir,id,  u"cd"+id+u".db")
        if (not os.path.exists(self.__databaseFileName)):
            raise SessionException,  u"No Session exists for "+unicode(id)
        self.__databaseConnection = sqlite3.connect(self.__databaseFileName)
        self.__databaseConnection.row_factory = sqlite3.Row
        cur = self.__databaseConnection.cursor()
        cur.execute('''select * from account a, jid j where j.id=a.id_jid''')
        for result in cur:
            a = Account(myid=result['id'],jid=result['jid'], server=result['server'], port=result['port'], resource=result['resource'], avatar=result['avatar'])
            self.__accounts.append(a)
        cur.close()
        self.__databaseConnection.close()

                                   
